<template>
  <div>
    <div class="wrap-citySearch">
      <input type="text" placeholder="输入" class="input" v-model="keyword">
    </div>
    <div class="search-content" ref="wrapper" v-show="keyword">
      <ul>
        <li v-for="item of list" class="item border-bottom" :key="item.id" @click="handleCityClick(item.name)">
          {{item.name}}
        </li>
        <li class="item border-bottom" v-show="haslist">none</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Becroll from 'better-scroll'

export default {
  name: 'citySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      // this.$store.dispatch('citychange',city)
      this.$store.commit('citychange', city)
      this.$router.push('/')
    }
  },
  mounted () {
    this.scroll = new Becroll(this.$refs.wrapper)
  },
  computed: {
    haslist () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/veribles.styl'
  .wrap-citySearch
    height: 0.72rem
    background: $bgColor
    padding: 0 0.1rem
    .input
      width: 100%
      height: 0.62rem
      padding: 0 0.1rem
      box-sizing border-box
      line-height: 0.62rem
      text-align: center
      border-radius 0.06rem
      background #fff

  .search-content
    position: absolute
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
    overflow hidden
    z-index 1
    .item
      line-height: 0.54rem
      color: #666
      background #fff
      padding-left: 0.4rem
</style>
